package unionfind;

/**
 * 并查集3
 * O(h)
 * 基于size的优化
 *
 * @author: yxyi
 * @mail: yxyi@iflytek.com
 * @date: 2019-01-14
 */
public class UnionFind3 implements UF {

    private int[] parent;
    private int[] size; // size[i] 表示已i为根的集合中元素个数

    public UnionFind3(int capaticy) {
        parent = new int[capaticy];
        size = new int[capaticy];
        for (int i = 0; i < capaticy; i++) {
            parent[i] = i;
            size[i] = 1;
        }
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElements(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }

        if (size[pRoot] < size[qRoot]) {
            parent[pRoot] = qRoot;
            size[pRoot] += size[qRoot];
        } else {
            parent[qRoot] = pRoot;
            size[qRoot] += size[pRoot];
        }

    }

    private int find(int p) {
        if (p < 0 || p >= parent.length) {
            throw new IllegalArgumentException("p is out of bound");
        }
        while (p != parent[p]) {
            p = parent[p];
        }
        return p;
    }
}
